/*
 * @描述: 
 * @创建者: kilomChou
 * @Date: 2021-05-03 21:06:51
 * @最后编辑: kilomChou
 * @LastEditTime: 2021-05-09 20:35:19
 */
import { _decorator, Component, Prefab, NodePool, instantiate, Sprite, math, tween, v3, easing } from 'cc';
import { ClientEvent, ED } from '../event/ClientEvent';
import { SnakeMod } from '../model/SnakeMod';
const { ccclass, property } = _decorator;


@ccclass('FoodMgr')
export class FoodMgr extends Component {

    @property(Prefab)
    foodPrefab: Prefab

    /** 食物节点对象池 */
    foodPool: NodePool = new NodePool();

    onLoad() {

        ED.on(ClientEvent.FOOD_LOAD, data => {
            //加载食物
            data.forEach(food => {
                let node = food.node = this.foodPool.get() || instantiate(this.foodPrefab);
                this.node.addChild(node);
                node.setPosition(food.x, food.y);
                node.setScale(0, 0);
                node.getComponent(Sprite).color = math.color(food.color);
                tween(food.node).to(0.33, { scale: v3(food.w, food.w) }, { easing: easing.quadOut }).start();
            })
        })

        ED.on(ClientEvent.FOOD_UNLOAD, data => {
            //卸载食物
            data.forEach(food => {
                let props: any = { scale: v3(0, 0) };
                if (food.eaterId) {
                    let snakeNode = SnakeMod.getSnakeNodeById(food.eaterId);
                    if (snakeNode && snakeNode.node) {
                        props.position = snakeNode.node.position;
                    }
                }
                tween(food.node)
                    .to(0.33, props, { easing: easing.quadOut })
                    .call(() => {
                        this.foodPool.put(food.node);
                    })
                    .start();
            })
        })
    }

    start() {


    }

}